#include <Python.h>
#include <stdio.h>
#include "pythonapi.h"
#include "pyjuku.h"
#include "jukuframe.h"

extern int footprints_allocated;

PythonApi::PythonApi()
:
m_command_handler(ID_MENU_PYTHON_COMMAND_FIRST, ID_MENU_PYTHON_COMMAND_LAST),
m_check_handler(ID_MENU_PYTHON_CHECK_FIRST, ID_MENU_PYTHON_CHECK_LAST),
m_char_handler(NULL),
m_special_handler(NULL)
{
	Py_Initialize();
	
	initjuku();
}

PythonApi::~PythonApi()
{
	Py_Finalize();
	/*
		Footprints that are added to the library are left allocated.
		TODO: fix?
	*/
	std::cerr<<"footprints_allocated="<<footprints_allocated<<std::endl;
	std::cerr<<"PyApiFootprints that are added to the library are currently left allocated."<<std::endl;
}

bool PythonApi::ExecFile(wxString path)
{
	fprintf(stderr, "PythonApi: Excecuting file %s\n", (const char*)path.fn_str());
	FILE *fp = fopen(path.fn_str(), "r");
	if(fp == NULL){
		fprintf(stderr, "PythonApi: Failed to open %s\n", (const char*)path.fn_str());
		return false;
	}
	PyRun_SimpleFile(fp, path.fn_str());
	fclose(fp);
	return true;
}

int PythonApi::AddMenuCommand(PyObject *obj)
{
	return m_command_handler.AddObject(obj);
}

void PythonApi::ExecMenuCommand(int id)
{
	fprintf(stderr, "PythonApi: Executing menu command: %i\n", id);
	PyObject *obj = m_command_handler.GetObject(id);
	if(obj==NULL){
		fprintf(stderr, "PythonApi::ExecMenuCommand(): item not found in callback list\n");
		return;
	}
	PyObject *result = PyEval_CallFunction(obj, "(i)", id);
	if(result == NULL){
		fprintf(stderr, "PythonApi::ExecMenuCommand(): Got an exception:\n");
		PyErr_Print();
		PyErr_Clear();
	}
	else
		Py_DECREF(result);
}

int PythonApi::AddMenuCheck(PyObject *obj)
{
	return m_check_handler.AddObject(obj);
}

void PythonApi::ExecMenuCheck(int id, bool checked)
{
	fprintf(stderr, "PythonApi: Executing menu check: %i: checked=%i\n", id, checked);
	PyObject *obj = m_check_handler.GetObject(id);
	if(obj==NULL){
		fprintf(stderr, "PythonApi::ExecMenuCheck(): item not found in callback list\n");
		return;
	}
	PyObject *result = PyEval_CallFunction(obj, "(ii)", id, checked);
	if(result == NULL){
		fprintf(stderr, "PythonApi::ExecMenuCheck(): Got an exception:\n");
		PyErr_Print();
		PyErr_Clear();
	}
	else
		Py_DECREF(result);
}


